using AutoMapper;
using B.S.XZYData.Api.Read.Application.Command.Role;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Role
{
    public class GetRolePageHandler : IRequestHandler<GetRolePageCommand, ApiPageing<RoleDto>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepo;
        private readonly IBaseRepository<PermissionRoleModel> _rolePermissionRepo;
        private readonly IBaseRepository<PermissionModel> _permissionRepo;
        private readonly IMapper _mapper;

        public GetRolePageHandler(
            IBaseRepository<RoleModel> roleRepo,
            IBaseRepository<PermissionRoleModel> rolePermissionRepo,
            IBaseRepository<PermissionModel> permissionRepo,
            IMapper mapper)
        {
            _roleRepo = roleRepo;
            _rolePermissionRepo = rolePermissionRepo;
            _permissionRepo = permissionRepo;
            _mapper = mapper;
        }

        public async Task<ApiPageing<RoleDto>> Handle(GetRolePageCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiPageing<RoleDto>();
            
            // 获取所有角色
            var roles = _roleRepo.GetAll().Where(x => !x.IsDeleted).ToList();
            
            // 过滤角色名称
            if (!string.IsNullOrEmpty(request.RoleName))
            {
                roles = roles.Where(x => x.RoleName.Contains(request.RoleName)).ToList();
            }
            
            res.TotaCount = roles.Count;
            res.TotaPage = (int)Math.Ceiling(res.TotaCount * 1.0 / request.Size);

            // 获取所有角色权限关系
            var rolePermissions = _rolePermissionRepo.GetAll().Where(rp => !rp.IsDeleted).ToList();
            
            // 获取所有权限
            var permissions = _permissionRepo.GetAll().Where(p => !p.IsDeleted).ToList();

            // 构建结果
            var result = new List<RoleDto>();
            foreach (var role in roles)
            {
                var rolePermissionIds = rolePermissions.Where(rp => rp.RoleId == role.Id).Select(rp => rp.PermissionId).ToList();
                var rolePermissionNames = permissions.Where(p => rolePermissionIds.Contains(p.Id)).Select(p => p.PermissionName).ToList();
                
                result.Add(new RoleDto
                {
                    Id = role.Id,
                    RoleName = role.RoleName,
                    PermissionIds = rolePermissionIds,
                    PermissionNames = rolePermissionNames,
                    CreateTime = role.CreateTime,
                    IsState = role.IsState,
                });
            }

            // 排序和分页
            res.PageData = result
                .OrderByDescending(x => x.CreateTime)
                .Skip((request.Index - 1) * request.Size)
                .Take(request.Size)
                .ToList();

            res.Msg = "查询角色列表成功!";
            res.Code = ApiEnum.Success;
            return await Task.FromResult(res);
        }
    }
} 